const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin 
    = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const glob = require('glob');

const HtmlWebpackExternalsPlugin = require('html-webpack-externals-plugin');

const webpack = require('webpack');

const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');

const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');

const setMPA = () => {
    const entry = {};
    const plugins = [];

    const entryFiles = glob.sync(path.join(__dirname, './src/*/index.js'));

    // 看视频评论后修改了一下, 使用 `Object.keys` 先处理一遍
    // 这样无论`entryFiles`是数组还是对象都能兼容下面的代码
    Object.keys(entryFiles).map( (key) => {
        const absoluteFilepath = entryFiles[key];
        const match = absoluteFilepath.match(/src\/(.*)\/index\.js/)
        const folderName = match && match[1];
        entry[folderName] = absoluteFilepath;
        plugins.push(
            new HtmlWebpackPlugin({
                template: path.join(__dirname, `src/${folderName}/index.html`),
                filename: `${folderName}.html`,
                chunks: [folderName, 'vendors'],
                inject: true,
                minify: {
                    html5: true,
                    collapseWhitespace: true,
                    preserveLineBreaks: false,
                    minifyCSS: true,
                    minifyJS: true,
                    removeComments: false
                }
            })
        );
    } );

    return {
        entry,
        plugins
    }
}

const { entry, plugins } = setMPA();

const SpeedMeasureWebpackPlugin = require('speed-measure-webpack-plugin');
const smp = new SpeedMeasureWebpackPlugin();

const WebpackBundleAnalyzer = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

const PurgecssPlugin = require('purgecss-webpack-plugin');

const PATHS = {
    src: path.join(__dirname, 'src')
};

// module.exports = smp.wrap({
module.exports = {
    entry: entry,
    output: {
        path: path.join(__dirname, '/dist'),
        filename: '[name]_[chunkhash:8].js'
    },
    mode: 'production', // production, development, none
    devtool: 'inline-source-map', // eval, source-map, inline-source-map, 
    // stats: 'errors-only', // errors-only, minimal, none, normal, verbose
    module: {
        rules: [
            {
                test: /\.js$/,
                include: path.resolve('src'),
                use: [
                    'babel-loader?cacheDirectory=true',
                    // 'eslint-loader'
                ]
            },
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                ]
            },
            {
                test: /\.less$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    {
                        loader: 'px2rem-loader',
                        options: {
                            remUnit: 75,
                            remPrecision: 8
                        }
                    },
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: () => [
                                require('autoprefixer')({
                                    overrideBrowserslist: ['last 2 version', '>1%', 'ios 7']
                                })
                            ]
                        }
                    },
                    'less-loader'
                ]
            },
            {
                test: /\.(png|jpe?g|gif|svg)$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name]_[contenthash:8].[ext]'
                        }
                    },
                ]
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)/,
                use: {
                    loader: 'file-loader',
                    options: {
                        name: '[name]_[hash:8].[ext]'
                    }
                }
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: '[name]_[contenthash:8].css'
        }),
        new OptimizeCssAssetsWebpackPlugin({
            assetNameRegExp: /\.css$/g,
            cssProcessor: require('cssnano')
        }),
        new CleanWebpackPlugin(),
        // new webpack.optimize.ModuleConcatenationPlugin(),
        new FriendlyErrorsWebpackPlugin(),
        function(){
            // webpack3
            // this.plugin('done', () => {})
            this.hooks.done.tap('done', (stats) => {
                if (stats.compilation.errors 
                    && stats.compilation.errors.length
                    && process.argv.indexOf('--watch') == -1) {
                    console.log('build error');
                    process.exit(1);
                }
            })
        },
        // new WebpackBundleAnalyzer(),
        // new webpack.DllReferencePlugin({
        //     manifest: require('./build/library/library.json')
        // }),
        new HardSourceWebpackPlugin(),
        new PurgecssPlugin({
            paths: glob.sync(`${PATHS.src}/**/*`,  { nodir: true }),
        }),
    ].concat(plugins),
    optimization: {
        splitChunks: {
            minSize: 0, // 0, 1000
            cacheGroups: {
                commons: {
                    // test: /(react|react-dom)/,
                    name: 'commons',
                    chunks: 'all',
                    minChunks: 3, // 2, 3
                }
            }
        }
    },
    resolve: {
        alias: {
            'react': path.resolve(__dirname, './node_modules/react/umd/react.production.min.js'),
            'react-dom': path.resolve(__dirname, './node_modules/react-dom/umd/react-dom.production.min.js'),
        },
        extensions: ['.js'],
        mainFields: ['main'],
    },
};
// });
